(function(){

  angular.module('object',[])
        .controller('ObjectController', [
          '$scope', '$stateParams', 'API', 'LxNotificationService', 'LxDialogService', ObjectController
        ])
        .filter('isChecked', function() {
          return function(input) {
            return input==1 ? "checked" : "";
          };
        });;

  /**
   * Main Controller for the Angular Material Starter App
   */
  function ObjectController( $scope, $stateParams, API, LxNotificationService, LxDialogService) {
    var objectName = $stateParams.objectName;

    var pageNumNow = 1;

    //配置项
    API.get({"object":objectName,"id":"config"},function(returnData){
      if(!returnData.error){
        console.log("配置项",returnData.data);
        $scope.objectConfig = returnData.data;

        $scope.index(1);

      }
    });

    //索引
    $scope.index = function(pageNum){
      pageNum = pageNum?pageNum:pageNumNow;
      pageNumNow = pageNum;

      API.query({"object":objectName,"pageNum":pageNum},function(returnData){
        if(!returnData.error){
          console.log("索引结果",returnData.data);
          $scope.objects = returnData.data;
        }
      });      
    }

    //单条记录
    $scope.show = function(object){
      if(object){
        API.get({"object":objectName,"id":object.id},function(returnData){
          if(!returnData.error){
            console.log("单条结果",returnData.data);
            $scope.object = returnData.data;
          }
        });  
      }else{
        $scope.object = {};
        angular.forEach($scope.objectConfig.fields,function(field){
          if(field.name == "created_at") field.default = null;
          if(field.name == "created_by") field.default = "1";
          if(field.default != null)
            $scope.object[field.name] = field.default;
        });
      }

      LxDialogService.open('showDialog');
    }

    //创建或更新
    $scope.store = function(object){
      console.log("提交内容",object);

      if(object.id){
        API.update({"object":objectName,"id":object.id},object,function(returnData){
          if(!returnData.error){
            console.log("更新结果",returnData.data);
            LxNotificationService.success('更新成功！');
            LxDialogService.close('showDialog');
          }else{
            LxNotificationService.error('更新失败！');
          }
          $scope.index();
        }); 

      }else{

        API.save({"object":objectName},object,function(returnData){
          if(!returnData.error){
            console.log("创建结果",returnData.data);
            LxNotificationService.success('创建成功！！');
            LxDialogService.close('showDialog');
          }else{
            LxNotificationService.error('创建失败！');
          }
          $scope.index();
        });

      }

    };

    //删除
    $scope.destroy = function(object){

      LxNotificationService.confirm('确定删除此记录？', '删除后不可恢复！', { cancel:'取消', ok:'删除' }, function(answer)
      {
        if(!answer) return false;
      
        API.delete({"object":objectName,"id":object.id},function(returnData){
          if(!returnData.error){
            console.log("删除结果",returnData.data);
            $scope.objects.splice($scope.objects.indexOf(object), 1);
            LxNotificationService.success('删除成功！');
          }else{
            LxNotificationService.error('删除失败！');
          }
        });

      });

    };

    //ajax关联项
    $scope.ajax = {
        selected: '',
        list: [],
        update: function(relate, newFilter, oldFilter)
        {
            if (newFilter)
            {
                $scope.ajax.loading = true;
                var relateTable  = relate.table;
                var relateSelect = relate.select;
                var filterStr = (relate.filter?relate.filter + " AND ":"") + relateTable + "." + relateSelect + " LIKE '%" + newFilter + "%'";

                API.query({"object":relateTable,"filter_str":filterStr,"no_relate":1},function(returnData){
                  if(!returnData.error){
                    console.log("关联查找结果",relateTable,returnData.data);
                    $scope.ajax.list = returnData.data;
                    $scope.ajax.loading = false;

                  }else{
                    $scope.ajax.loading = false;
                  }
                },function(){
                    $scope.ajax.loading = false;
                });
            }
            else
            {
                $scope.ajax.list = false;
            }
        },
        toModel: function(relate, data, callback)
        {
            if (data)
            {
                callback(data[relate.field]);
            }
            else
            {
                callback();
            }
        },
        toSelection: function(relate, data, callback)
        {
            if (data)
            {
                var relateTable  = relate.table;
                var relateFiled = relate.field;
                var filterStr = (relate.filter?relate.filter + " AND ":"") + relateTable + "." + relateFiled + " = '" + data+"'";

                API.query({"object":relateTable,"filter_str":filterStr,"no_relate":1},function(returnData){
                  if(!returnData.error){
                    console.log("关联查找结果",relateTable,returnData.data);
                    callback(returnData.data[0]);
                  }else{
                    callback();
                  }
                },function(){
                   callback();
                });
            }
            else
            {
                callback();
            }
        },
        loading: false
    };

    //类型判断
    $scope.typeFileter = function(type){
      if(type.substr(0,7) == "varchar"){
        var varcharLength = type.substr(8,type.length-9);
        if(varcharLength < 100)
          return "input";
        else
          return "textarea";
      
      }else if(type.substr(0,3) == "int" || type.substr(0,8) == "smallint"){
        return "int";
      }else if(type == "tinyint(1)"){
        return "bool";
      }else{
        return type;
      }

    }

  }
  

})();
